package com.boulderai.mcp.controller;

import com.boulderai.mcp.service.McpService;
import com.boulderai.mcp.model.Tool;
import com.boulderai.mcp.model.Resource;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * MCP REST控制器
 * 提供MCP相关的HTTP API接口和管理界面
 */
@Controller
@CrossOrigin(origins = "*", maxAge = 3600)
public class McpController {

    @Autowired
    private McpService mcpService;

    /**
     * MCP管理界面
     */
    @GetMapping("/admin")
    public String adminPage(Model model) {
        model.addAttribute("title", "MCP Client 管理界面");
        return "mcp-admin";
    }

    /**
     * API文档页面
     */
    @GetMapping("/api-docs")
    public String apiDocsPage(Model model) {
        model.addAttribute("title", "MCP API 文档");
        return "api-docs";
    }

    /**
     * 连接到MCP服务器
     */
    @PostMapping("/api/mcp/connect")
    @ResponseBody
    public CompletableFuture<ResponseEntity<String>> connect(@RequestBody ConnectRequest request) {
        // 为REST API生成临时会话ID
        String sessionId = "rest-session-" + System.currentTimeMillis();
        return mcpService.connect(sessionId, request.getServerUri())
                .thenApply(result -> ResponseEntity.ok("Connected successfully"))
                .exceptionally(ex -> ResponseEntity.badRequest().body("Connection failed: " + ex.getMessage()));
    }

    /**
     * 断开连接
     */
    @PostMapping("/api/mcp/disconnect/{sessionId}")
    @ResponseBody
    public CompletableFuture<ResponseEntity<String>> disconnect(@PathVariable String sessionId) {
        return mcpService.disconnect(sessionId)
                .thenApply(result -> ResponseEntity.ok("Disconnected successfully"))
                .exceptionally(ex -> ResponseEntity.badRequest().body("Disconnect failed: " + ex.getMessage()));
    }

    /**
     * 获取连接状态
     */
    @GetMapping("/api/mcp/status/{sessionId}")
    @ResponseBody
    public ResponseEntity<ConnectionStatus> getStatus(@PathVariable String sessionId) {
        boolean connected = mcpService.isConnected(sessionId);
        return ResponseEntity.ok(new ConnectionStatus(connected));
    }

    /**
     * 初始化会话
     */
    @PostMapping("/api/mcp/initialize/{sessionId}")
    @ResponseBody
    public CompletableFuture<ResponseEntity<JsonNode>> initialize(@PathVariable String sessionId, @RequestBody JsonNode clientInfo) {
        return mcpService.initialize(sessionId, clientInfo)
                .thenApply(ResponseEntity::ok)
                .exceptionally(ex -> ResponseEntity.badRequest().build());
    }

    /**
     * 获取工具列表
     */
    @GetMapping("/api/mcp/tools/{sessionId}")
    @ResponseBody
    public CompletableFuture<ResponseEntity<List<Tool>>> listTools(@PathVariable String sessionId) {
        return mcpService.listTools(sessionId)
                .thenApply(ResponseEntity::ok)
                .exceptionally(ex -> ResponseEntity.badRequest().build());
    }

    /**
     * 调用工具
     */
    @PostMapping("/api/mcp/tools/{sessionId}/{toolName}/call")
    @ResponseBody
    public CompletableFuture<ResponseEntity<JsonNode>> callTool(
            @PathVariable String sessionId,
            @PathVariable String toolName,
            @RequestBody JsonNode arguments) {
        return mcpService.callTool(sessionId, toolName, arguments)
                .thenApply(ResponseEntity::ok)
                .exceptionally(ex -> ResponseEntity.badRequest().build());
    }

    /**
     * 获取资源列表
     */
    @GetMapping("/api/mcp/resources/{sessionId}")
    @ResponseBody
    public CompletableFuture<ResponseEntity<List<Resource>>> listResources(@PathVariable String sessionId) {
        return mcpService.listResources(sessionId)
                .thenApply(ResponseEntity::ok)
                .exceptionally(ex -> ResponseEntity.badRequest().build());
    }

    /**
     * 读取资源
     */
    @GetMapping("/api/mcp/resources/{sessionId}/{resourceUri}")
    @ResponseBody
    public CompletableFuture<ResponseEntity<JsonNode>> readResource(@PathVariable String sessionId, @PathVariable String resourceUri) {
        return mcpService.readResource(sessionId, resourceUri)
                .thenApply(ResponseEntity::ok)
                .exceptionally(ex -> ResponseEntity.badRequest().build());
    }

    /**
     * 发送自定义请求
     */
    @PostMapping("/api/mcp/request/{sessionId}")
    @ResponseBody
    public CompletableFuture<ResponseEntity<JsonNode>> sendRequest(@PathVariable String sessionId, @RequestBody CustomRequest request) {
        return mcpService.sendRequest(sessionId, request.getMethod(), request.getParams())
                .thenApply(ResponseEntity::ok)
                .exceptionally(ex -> ResponseEntity.badRequest().build());
    }

    // 内部类定义请求和响应模型
    public static class ConnectRequest {
        private String serverUri;

        public String getServerUri() {
            return serverUri;
        }

        public void setServerUri(String serverUri) {
            this.serverUri = serverUri;
        }
    }

    public static class ConnectionStatus {
        private boolean connected;

        public ConnectionStatus(boolean connected) {
            this.connected = connected;
        }

        public boolean isConnected() {
            return connected;
        }

        public void setConnected(boolean connected) {
            this.connected = connected;
        }
    }

    public static class CustomRequest {
        private String method;
        private JsonNode params;

        public String getMethod() {
            return method;
        }

        public void setMethod(String method) {
            this.method = method;
        }

        public JsonNode getParams() {
            return params;
        }

        public void setParams(JsonNode params) {
            this.params = params;
        }
    }
}